package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.SexEnum;
import com.xmy.cultivate.enums.StatusStaffEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.AppointSchoolMapper;
import com.xmy.cultivate.mapper.RoleAdminMapper;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 员工 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-26
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {


    @Autowired
    @Lazy
    IAdminService iAdminService;

    @Autowired
    @Lazy
    IRoleAdminService iRoleAdminService;

    @Autowired
    @Lazy
    IAppointSchoolService iAppointSchoolService;

    @Autowired
    @Lazy
    AppointSchoolMapper appointSchoolMapper;

    @Autowired
    @Lazy
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    RoleAdminMapper roleAdminMapper;

    @Autowired
    @Lazy
    IRoleService iRoleService;

    @Autowired
    @Lazy
    IDictService iDictService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    IOrganizationStaffService iOrganizationStaffService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ITeacherLeadsYearClassService iTeacherLeadsYearClassService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IStudentService iStudentService;

    @Transactional
    public boolean saveTo(Staff staff) {
        Long adminId = idWorker.nextId();
        Admin admin = staff.getAdminObj();
        if (admin.getAccount() != null && !admin.getAccount().isEmpty()) {
            String account = admin.getAccount();
            long count = iAdminService.count(new QueryWrapper<Admin>().eq("account", account));
            if (count > 0) {
                throw new CommonException(ResultCode.ACCOUNT_IN);
                //throw new CommonException(ResultCode.quarterNo);
            }

            admin.setId(adminId);
            //boolean rs = CommonUtil.isPasswordAvailable("",admin.getPwd());
            //if (!rs){
                //throw new CommonException(ResultCode.PWD_EASY);
            //}

            String pwd = new Md5Hash(admin.getPwd(), admin.getAccount(), 3).toString();
            admin.setPwd(pwd);
            iAdminService.save(admin);

            //机构账号，管辖校区
            List<AppointSchool> appointSchoolList = new ArrayList<>();
            for (Long item : admin.getSchoolIdList()) {
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(adminId);
                appointSchool.setSchoolId(item);
                appointSchool.setType(2);//机构帐号指定校区
                appointSchoolList.add(appointSchool);
            }
            //机构账号，角色
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item : admin.getRoleIdList()) {
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(adminId);
                roleAdminList.add(roleAdmin);
            }

            if (!appointSchoolList.isEmpty()) {
                iAppointSchoolService.saveBatch(appointSchoolList, appointSchoolList.size());
            }
            if (!roleAdminList.isEmpty()) {
                iRoleAdminService.saveBatch(roleAdminList, roleAdminList.size());
            }
        }

        staff.setId(adminId);
        staff.setAdminId(adminId);

        //所属部门
        List<OrganizationStaff> organizationStaffList = new ArrayList<>();
        //老师，上课校区范围
        List<AppointSchool> scopeSchoolList = new ArrayList<>();

        for (Long id : staff.getDepartIdList()) {
            OrganizationStaff organizationStaff = new OrganizationStaff();
            organizationStaff.setOrganizationId(id);
            organizationStaff.setStaffId(staff.getId());
            organizationStaffList.add(organizationStaff);
        }

        for (Long id : staff.getScopeSchoolIdList()) {
            AppointSchool appointSchool = new AppointSchool();
            appointSchool.setSchoolId(id);
            appointSchool.setForId(staff.getId());
            appointSchool.setType(4);
            scopeSchoolList.add(appointSchool);
        }

        Long id = staff.getId();
        //删除老师带班年级
        QueryWrapper<TeacherLeadsYearClass> teacherLeadsYearClassQueryWrapper = new QueryWrapper<>();
        teacherLeadsYearClassQueryWrapper.eq("teacher_id", id);
        iTeacherLeadsYearClassService.remove(teacherLeadsYearClassQueryWrapper);
        List<TeacherLeadsYearClass> teacherLeadsYearClassIdList = new ArrayList<>();
        for (Integer item : staff.getTeacherLeadsYearClassIdList()){
            TeacherLeadsYearClass teacherLeadsYearClass = new TeacherLeadsYearClass();
            teacherLeadsYearClass.setTeacherId(id);
            teacherLeadsYearClass.setYearClassId(item);
            teacherLeadsYearClassIdList.add(teacherLeadsYearClass);
        }
        if (teacherLeadsYearClassIdList.size() > 0) {
            iTeacherLeadsYearClassService.saveBatch(teacherLeadsYearClassIdList, teacherLeadsYearClassIdList.size());
        }

        if (!organizationStaffList.isEmpty()) {
            iOrganizationStaffService.saveBatch(organizationStaffList, organizationStaffList.size());
        }
        if (!scopeSchoolList.isEmpty()) {
            iAppointSchoolService.saveBatch(scopeSchoolList, scopeSchoolList.size());
        }

        this.save(staff);
        if (staff.getPhone().length() == 11){
            //电话号码如果变了，更新企业微信号
            iMqPushService.updateQyWecharId(staff);
        }

        return true;
    }

    @Transactional
    public boolean updateTo(Staff staff) {
        Admin admin = staff.getAdminObj();
        Long adminId = staff.getId();

        Staff staffOld = this.getById(staff.getId());
        if (!Objects.isNull(staffOld)){
            if (staffOld.getPhone() != staff.getPhone()){
                if (staff.getPhone().length() == 11){
                    //电话号码如果变了，更新企业微信号
                    iMqPushService.updateQyWecharId(staff);
                }
            }
        }

        /*if (staff.getStatus().equals(StatusStaffEnum.OUT)) {
            staff.setLeaveDate(LocalDate.now());
        } else{
            staff.setLeaveDate(null);
        }*/

        if (admin != null && admin.getId() != null) {
            String account = admin.getAccount();
            Admin adminOld = iAdminService.getById(staff.getId());
            Long count = iAdminService.count(new QueryWrapper<Admin>().eq("account", account).ne("account", adminOld.getAccount()));

            if (count > 0) {
                throw new CommonException(ResultCode.ACCOUNT_IN);
                //throw new CommonException(ResultCode.quarterNo);
            }

            admin.setId(staff.getId());
            if (StringUtils.isNotBlank(admin.getPwd())) {
                boolean rs = CommonUtil.isPasswordAvailable("",admin.getPwd());
                if (!rs){
                    throw new CommonException(ResultCode.PWD_EASY);
                }

                String pwd = new Md5Hash(admin.getPwd(), admin.getAccount(), 3).toString();
                admin.setPwd(pwd);
            }else {
            admin.setPwd(adminOld.getPwd());
        }

            Long id = staff.getId();
            //删除老师带班年级
            QueryWrapper<TeacherLeadsYearClass> teacherLeadsYearClassQueryWrapper = new QueryWrapper<>();
            teacherLeadsYearClassQueryWrapper.eq("teacher_id", id);
            iTeacherLeadsYearClassService.remove(teacherLeadsYearClassQueryWrapper);
            List<TeacherLeadsYearClass> teacherLeadsYearClassIdList = new ArrayList<>();
            for (Integer item : staff.getTeacherLeadsYearClassIdList()){
                TeacherLeadsYearClass teacherLeadsYearClass = new TeacherLeadsYearClass();
                teacherLeadsYearClass.setTeacherId(id);
                teacherLeadsYearClass.setYearClassId(item);
                teacherLeadsYearClassIdList.add(teacherLeadsYearClass);
            }
            if (teacherLeadsYearClassIdList.size() > 0) {
                iTeacherLeadsYearClassService.saveBatch(teacherLeadsYearClassIdList, teacherLeadsYearClassIdList.size());
            }



            //iAdminService.updateById(admin);

            iAdminService.updateById(admin);
            //先删除指定校区
            QueryWrapper<AppointSchool> delAppointSchoolQueryWrapper = new QueryWrapper<>();
            delAppointSchoolQueryWrapper.eq("for_id", admin.getId()).eq("type", 2);
            appointSchoolMapper.delete(delAppointSchoolQueryWrapper);

            if (admin.getGovernMode().equals(3)){
                //所属校区
                List<Long> schoolIdList = new ArrayList<>();
                schoolIdList.add(staff.getSchoolId());
                admin.setSchoolIdList(schoolIdList);
            }
            List<AppointSchool> appointSchoolList = new ArrayList<>();
            for (Long item : admin.getSchoolIdList()) {
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(staff.getId());
                appointSchool.setSchoolId(item);
                appointSchool.setType(2);//机构帐号指定校区
                appointSchoolList.add(appointSchool);
            }
            //先删除角色
            QueryWrapper<RoleAdmin> roleAdminQueryWrapper = new QueryWrapper<>();
            roleAdminQueryWrapper.eq("admin_id", admin.getId());
            roleAdminMapper.delete(roleAdminQueryWrapper);
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item : admin.getRoleIdList()) {
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(admin.getId());
                roleAdminList.add(roleAdmin);
            }
            if (appointSchoolList.size() > 0) {
                iAppointSchoolService.saveBatch(appointSchoolList, appointSchoolList.size());
            }
            if (roleAdminList.size() > 0) {
                iRoleAdminService.saveBatch(roleAdminList, roleAdminList.size());
            }
        } else  if (admin != null){
            String account = admin.getAccount();
            if (StringUtils.isNotBlank(account)) {
                Long count = iAdminService.count(new QueryWrapper<Admin>().eq("account", account));
                if (count > 0) {
                    throw new CommonException(ResultCode.ACCOUNT_IN);
                    //throw new CommonException(ResultCode.quarterNo);
                }
            }

            admin.setId(adminId);
            staff.setAdminId(adminId);
            //boolean rs = CommonUtil.isPasswordAvailable("",admin.getPwd());
            //if (!rs){
                //throw new CommonException(ResultCode.PWD_EASY);
            //}
            String pwd = new Md5Hash(admin.getPwd(), admin.getAccount(), 3).toString();
            admin.setPwd(pwd);
            iAdminService.save(admin);
            if (admin.getGovernMode().equals(3)){
                //所属校区
                List<Long> schoolIdList = new ArrayList<>();
                schoolIdList.add(staff.getSchoolId());
                admin.setSchoolIdList(schoolIdList);
            }

            //机构账号，管辖校区
            List<AppointSchool> appointSchoolList = new ArrayList<>();
            for (Long item : admin.getSchoolIdList()) {
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(adminId);
                appointSchool.setSchoolId(item);
                appointSchool.setType(2);//机构帐号指定校区
                appointSchoolList.add(appointSchool);
            }
            //机构账号，角色
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item : admin.getRoleIdList()) {
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(adminId);
                roleAdminList.add(roleAdmin);
            }

            if (appointSchoolList.size() > 0) {
                iAppointSchoolService.saveBatch(appointSchoolList, appointSchoolList.size());
            }
            if (roleAdminList.size() > 0) {
                iRoleAdminService.saveBatch(roleAdminList, roleAdminList.size());
            }
        }

        //所属部门(需求变动，不需要此功能)
        //List<OrganizationStaff> organizationStaffList = new ArrayList<>();
        //老师，上课校区范围
        List<AppointSchool> scopeSchoolList = new ArrayList<>();

        /*for (Long id : staff.getDepartIdList()) {
            OrganizationStaff organizationStaff = new OrganizationStaff();
            organizationStaff.setOrganizationId(id);
            organizationStaff.setStaffId(staff.getId());
            organizationStaffList.add(organizationStaff);
        }*/

        if (staff.getScopeSchoolIdList() != null) {
            for (Long id : staff.getScopeSchoolIdList()) {
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setSchoolId(id);
                appointSchool.setForId(staff.getId());
                appointSchool.setType(4);
                scopeSchoolList.add(appointSchool);
            }
        }
        //先删除部门
        /*iOrganizationStaffService.remove(new QueryWrapper<OrganizationStaff>().eq("staff_id", staff.getId()));
        if (organizationStaffList.size() > 0) {
            iOrganizationStaffService.saveBatch(organizationStaffList, organizationStaffList.size());
        }*/

        //先删除上课校区范围指定校区
        iAppointSchoolService.remove(new QueryWrapper<AppointSchool>().eq("for_id", staff.getId()).eq("type", 4));
        if (scopeSchoolList.size() > 0) {
            iAppointSchoolService.saveBatch(scopeSchoolList, scopeSchoolList.size());
        }
        //staff.setId(adminId);

        Dict dict = iDictService.getDictByNumAndType(staff.getCourseInId(), 20);
        if (dict != null) {
            staff.setCourseInMoney(dict.getMoney());
            staff.setCourseInCount(dict.getCount());
        }
        this.updateById(staff);

        Student student = iStudentService.getById(staff.getId());
        if (Objects.isNull(student)){
            student = new Student();
            Integer yearClassId = 0;
            for (Integer item : staff.getTeacherLeadsYearClassIdList()){
                yearClassId = item;
            }
            student.setId(staff.getId());
            student.setName(staff.getName());
            student.setLinkmanPhone(staff.getPhone());
            student.setLinkman(staff.getName());
            student.setSchoolId(staff.getSchoolId());
            List<TypeValueData> typeValueDataList = new ArrayList<>();
            TypeValueData typeValueData = new TypeValueData();
            typeValueData.setTypeId(3);
            typeValueData.setContent(staff.getPhone());
            typeValueDataList.add(typeValueData);
            student.setLinkManList(typeValueDataList);
            student.setGradeId(yearClassId);
            student.setYearClassId(yearClassId);
            iStudentService.addOrUpdateData(student);
        }

        return true;
    }

    public Staff findOneById(Long id) {
        Staff staff = staffMapper.findOneById(id);

        List<Long> departIdList = appointSchoolMapper.getSchoolIdListForForId(staff.getId(), 3);
        List<Long> scopeSchoolIdList = appointSchoolMapper.getSchoolIdListForForId(staff.getId(), 4);
        staff.setDepartIdList(departIdList);
        staff.setScopeSchoolIdList(scopeSchoolIdList);
        Admin admin = staff.getAdminObj();
        if (admin != null) {
            List<Long> schoolIdList = appointSchoolMapper.getSchoolIdListForForId(admin.getId(), 2);
            List<Long> roleIdList = roleAdminMapper.getRoleIdListForAdminId(admin.getId());
            admin.setSchoolIdList(schoolIdList);
            admin.setRoleIdList(roleIdList);
        }
        return staff;
    }

    @Override
    public Integer staffCountByPhone(String phone) {
        Integer staffCount = staffMapper.staffCountByPhone(phone);
        return staffCount;
    }

    /**
     * 获取一条数据
     * @param id
     * @return
     */
    @Override
    public Staff getOneById(Long id){
        Staff staff = staffMapper.selectById(id);
        if (staff == null && id.equals(1568138350324350975L)){
            staff = new Staff();
            staff.setId(id);
            staff.setName("超级管理员");
            staff.setIsTeacher(0);
            staff.setSex(SexEnum.MAN);
            staff.setStatus(StatusStaffEnum.IN);
        }
        return staff;
    }


    public IPage<Staff> findAll(IPage<?> page, Wrapper wrapper) {

        IPage<Staff> staffIPage = staffMapper.findAll(page, wrapper);
        for (Staff staff : staffIPage.getRecords()) {
            if (staff.getAdminObj() != null) {
                Admin admin = staff.getAdminObj();
                List<Role> roleList = iRoleService.list(new QueryWrapper<Role>().inSql("id", "select role_id from role_admin where admin_id=" + admin.getId()));
                admin.setRoleList(roleList);
            }
        }

        return staffIPage;
    }

    /**
     * 根据教师编号获取教师名称
     *
     * @param id
     * @return
     */
    @Override
    public String getNameById(Long id) {
        return staffMapper.getNameById(id);
    }

    /**
     * 获取差集
     *
     * @param page
     * @param wrapper
     * @return
     */
    @Override
    public Page<Staff> listCollection(IPage<?> page, Wrapper wrapper) {
        return staffMapper.listCollection(page, wrapper);
    }

    @Override
    public Staff getOneForAdminid(Long adminId){
        return staffMapper.getOneForAdminid(adminId);
    }

    @Override
    public List<Staff> working(Wrapper wrapper) {
        return staffMapper.working(wrapper);
    }

    @Override
    public List<Staff> staffAnalyse(String quarterNum, String yearPart, String roleId, String name, String schoolId,String subjectId) {
        return staffMapper.staffAnalyse(quarterNum,yearPart,roleId,name,schoolId,subjectId);
    }


    @Override
    public List<String> getSiginSubjects(Staff staffOld, Integer lessonType){
        Quarter quarterNow = iQuarterService.getNowQuarter();

        Staff staffInfo = this.getOneById(staffOld.getId());

        List<String> subjectsId = new ArrayList<>();
        /**
         * 是教师
         */
        if (staffInfo.getIsTeacher() != null && staffInfo.getIsTeacher().equals(1)){
            Grade grade = iGradeService.getGradeOneForTeacherId(quarterNow.getYearPart(),quarterNow.getNum(),staffInfo.getId(),lessonType);
            if (grade!=null){
                subjectsId.add(grade.getSubjectsId().toString());
            }else {
                String subjects = staffInfo.getSiginSubjects();
                if (StringUtils.isNotBlank(subjects)){
                    subjectsId = Arrays.asList(subjects.split(","));
                }
            }
        }else {
            //非教师
            String subjects = staffInfo.getSiginSubjects();
            if (StringUtils.isNotBlank(subjects)){
                subjectsId = Arrays.asList(subjects.split(","));
            }
        }
        return  subjectsId;
    }

    /**
     * 获取签到的科目类型
     * @param staffOld
     * @param lessonType
     * @return
     */
    @Override
    public Integer getSiginSubjectsType(Staff staffOld, Integer lessonType){
        Quarter quarterNow = iQuarterService.getNowQuarter();
        Staff staffInfo = this.getOneById(staffOld.getId());
        Integer type = 0;
        /**
         * 是教师
         */
        if (staffInfo.getIsTeacher() != null && staffInfo.getIsTeacher().equals(1)){
            Grade grade = iGradeService.getGradeOneForTeacherId(quarterNow.getYearPart(),quarterNow.getNum(),staffInfo.getId(),lessonType);
            if (grade!=null){
                type = 1;
            }
        }
        return  type;
    }


    @Override
    public List<Long> getTeacherIdForSubjects(String subjectsIds){
        return staffMapper.getTeacherIdForSubjects(subjectsIds);
    }

}
